/*
 *  功能管理
 */
var editObj = null, ptable = null, treeGrid = null, tableId = 'treeTable', layer = null;
layui.use(['element', 'table', 'tree', 'treeGrid', 'zlpoptree', 'zlPopSourceForm', 'zlSelectEx', 'zlPinYin', 'zlFormulaCmp'], function (exports) {
    var $ = layui.$
        , zlContext = layui.zlContext
        , layer = layui.layer
        , zlConfig = layui.zlConfig
        , statusName = zlConfig.global.result.statusName
        , msgName = zlConfig.global.result.msgName
        , OK = zlConfig.global.result.okState
        , form = layui.form
        , treeGrid = layui.treeGrid
        , zlPinYin = layui.zlPinYin
        , tableId = 'treeTable'
        , fullheight
        , isloadsearch = false
        , zlFormulaCmp = layui.zlFormulaCmp
        , coreTable = function () {
        };
    fullheight = zlContext.setMaxHeihgt(0);
    var param = {
        dataurl: layui.cache['contentPath'] + '/manager/coremodeldesign/query',
        method: 'post',
        formtitle: '选择表单',
    };

    var jsonBiaoD = JSON.stringify(param);
    var frm = [
        '<div class="layui-tab layui-tab-card layui-col-md12">'
        , '  <ul class="layui-tab-title">'
        , '   <li class="layui-this">通用信息</li>'
        , '  </ul>'
        , '  <div class="layui-tab-content">'
        , '     <div id="tabField" class="layui-tab-item layui-show">'
        , '        <form class="layui-form " style="margin:8px" id="addnew" >'
        , '         <input type="hidden" name="ORGID">'
        , '         <input type="hidden" name="RWID">'
        , '         <input type="hidden" name="type">'
        , '         <input type="hidden" name="VISIBILITY">'
        , '         <input type="hidden" name="SELORGID">'
        , '         <input type="hidden" name="dapinginput">'
        , '         <div class="layui-form-item">'
        , '	            <div class="layui-col-md12 ">'
        , '	      	        <label class="layui-form-label">名称</label>'
        , '	      	        <div class="layui-input-block">'
        , '	      		          <input type="text" class="layui-input" lay-filter="OBJNAME" name="OBJNAME" maxlength="40" lay-verify="required"> '
        , '                 </div>'
        , '	             </div>'
        , '         </div>'
        , '         <div class="layui-form-item">'
        , '	            <div class="layui-col-md12 ">'
        , '	      	        <label class="layui-form-label">编号</label>'
        , '	      	        <div class="layui-input-block">'
        , '	      		          <input type="text" class="layui-input" lay-filter="OBJCODE" name="OBJCODE" maxlength="20" lay-verify="required"> '
        , '                 </div>'
        , '	            </div>'
        , '         </div>'
        , '        <div class="layui-form-item">'
        , '     	      <div class="layui-col-md12">'
        , '     		        <label class="layui-form-label">功能链接</label>'
        , '     		        <div class="layui-input-block">'
        , '     			        <input type="text" class="layui-input" lay-filter="RES_ACTION" lay-verify=""  name="RES_ACTION" maxlength="100"> '
        , '                         <button class="layui-btn layui-btn-sm layui-hide" lay-filter="selReport">报表</button>'
        , '                         <button class="layui-btn layui-btn-sm layui-hide" lay-filter="selModel">模型</button>'
        , '                     </div>'
        , '     	       </div>'
        , '        </div>'
        , '        <div class="layui-form-item">'
        , '                 <div class="layui-col-md12">'
        , '                     <label name="pfunction" class="layui-form-label">上级功能</label>'
        , '                     <div class="layui-input-block">'
        , '                         <div name="SYS_PARENTID" zlcomponent class="layui-form-select zlpoptree" text="" value="" settings="{dataurl:\'' + layui.cache['contentPath'] + '/manager/corefunction/query\',method:\'post\',formtitle:\'选择上级功能\'}">'
        , '                         </div>'
        , '                     </div>'
        , '                 </div>'
        , '        </div>'
        , '        <div class="layui-form-item">'
        , '                 <div class="layui-col-md12">'
        , '                     <label name="pfunction" class="layui-form-label">选择表单</label>'
        , '                     <div class="layui-input-block">'
        , '                         <div name="RELE_RES_ID" zlcomponent class="layui-form-select zlpoptree" value=""  settings=' + jsonBiaoD + ' callback="' + `
                function(data) {
                    var pagerModelId=data[0].RWID;

                    var isBigCreen=function(modelId){
                        var param={
                            modelId:modelId,
                            designModel:true
                        },
                        ret=null;
                        $.ajax({
                            url: layui.cache['contentPath'] + \'/manager/coremodelshow/queryJson\',
                            type: 'get',
                            async: false,
                            data: param,
                            dataType: 'json',
                            success: function (res) {
                                if(res.state=='OK'){
                                    ret=!!JSON.parse(res.obj).isbigscreen;
                                }else{
                                    zlContext.errorMsg(res.msg);  
                                }                                                      
                            }
                        });
                        return ret;
                    }(pagerModelId);
                    var isnewtab='';
                    if (isBigCreen){
                        isnewtab='&isnewtab=1';
                    }
                   
                    if(data){
                        $(\'input[name=dapinginput]\').val(\'\');
                        $(\'select[name=daping]\').val(\'\');
                        $(\'input[name=RES_ACTION]\').attr(\'disabled\', \'disabled\');
                        $(\'input[name=RES_ACTION]\').val(\'#{contentpath}/manager/coremodelshow/?modelId=\' + data[0].RWID + isnewtab);
                    }else{
                            $(\'input[name=RES_ACTION]\').removeAttr(\'disabled\');
                    }
                    form.render(\'select\')
                    }`+ '" >'
        , '         </div>'
        , '                     </div>'
        , '                 </div>'
        , '        </div>'
        // , '        <div class="layui-form-item">'
        // , '                 <div class="layui-col-md12">'
        // , '                     <label name="pdfunction" class="layui-form-label">选择大屏</label>'
        // , '                     <div class="layui-input-block">'
        // , '                         <select lay-filter="daping" onchange="func()" name="daping" zlcomponent class="select-ext" settings="{placeholder:\'如果需要大屏展示请选择\', titlefield: \'OBJNAME\', valuefield: \'RWID\', method:\'POST\',dataurl:\'' + layui.cache['contentPath'] + '/manager/largescreen/query\'}"></select>'
        // , '                     </div>'
        // , '                 </div>'
        // , '        </div>'
        , '        <div class="layui-form-item">'
        , '     	      <div class="layui-col-md12">'
        , '     		        <label class="layui-form-label">是否需要登录</label>'
        , '     		        <div class="layui-input-block">'
        , '	  			            <input type="radio" name="ISLOGIN" value="1" title="是" >'
        , '				            <input type="radio" name="ISLOGIN" value="2" title="否" >'
        , '     	            </div>'
        , '                 </div>'
        , '        </div>'     
        , '        <div class="layui-form-item">'
        , '     	      <div class="layui-col-md12">'
        , '     		        <label class="layui-form-label">备注</label>'
        , '     		        <div class="layui-input-block">'
        , '     			        <input class="layui-input" lay-filter="BEIZ" name="BEIZ" maxlength="150"> </div>'
        , '     	      </div>'
        , '        </div>'
        , '        <div class="layui-form-item">'
        , '     	      <div class="layui-col-md12">'
        , '                     <div zl-action="formula"zl-action="formula" name="formula" zlcomponent class="zl-formulacmp"></div>'
        , '     		        <label class="layui-form-label">数据过滤规则(公式模式)</label>'
        , '     		        <div class="layui-input-block">'
        , '                         <button class="layui-btn custom-formula-btn layui-btn-sm" type="button" style="width:75px">自定义</button>'
        , '     			        <div id="ace-editor-contianer"></div>'
        , '                     </div>'
        , '     	      </div>'
        , '        </div>'
        , '        <div class="layui-form-item">'
        , '            <div class="layui-input-block">'
        , '              <button class="layui-btn" lay-submit  id="btnadd"  lay-filter="addfunction">保存</button>'
        , '            </div>'
        , '        </div>'
        , '     </form>'
        , '     </div>'
        , '     <div id="tabField" class="layui-tab-item layui-show">'
        , '     </div>'
        , ' </div>'
        , '</div>'
    ];
    var formindex,
        newFormObj = {},

        loadingLayer = layer.msg('数据查询中，请稍候...', { icon: 16, time: false, shade: 0.1 }),
        ptable = treeGrid.render({
            id: tableId
            , elem: '#' + tableId
            , method: 'post'
            , cellMinWidth: 100
            , height: fullheight
            , url: layui.cache['contentPath'] + '/manager/corefunction/query'
            , idField: 'RWID'
            , treeId: 'RWID'//树形id字段名称
            , treeUpId: 'SYS_PARENTID'//树形父id字段名称
            , treeShowName: 'OBJNAME'//以树形式显示的字段
            , isOpenDefault: false
            , chkboxType: { "Y": "", "N": "" }//父子节点的关联关系 默认值：{ "Y": "ps", "N": "ps" }
            , loading: false
            , cols: [[
                { type: 'numbers', fixed: '' }
                , { type: 'checkbox', fixed: '' }
                , { field: 'OBJNAME', width: '175', title: '名称', sort: true }
                , { field: 'OBJCODE', width: '155', title: '编号', sort: true }
                , { field: 'RES_ACTION', width: '275', title: '功能链接' }
                , { field: 'BEIZ', width: '300', title: '备注' }
                , { field: 'DATAFILTER', width: '300', title: '数据过滤规则' }
            ]]
            , page: false
            , response: zlConfig.global.gridResponse
            , done: function (res, curr, count) {
                layer.close(loadingLayer)
            }
        });
    function func() {
    }
    //展开或折叠全部
    $('#btnopenall').on('click', function () {
        var treedata = treeGrid.getDataTreeList('treeTable');
        if ($(this).find('i').hasClass("layui-icon-down")) {
            $(this).find('i').removeClass("layui-icon-down").addClass("layui-icon-up");
            $(this).find('span').text("收起全部")
        } else {
            $(this).find('i').removeClass("layui-icon-up").addClass("layui-icon-down");
            $(this).find('span').text("展开全部")
        }
        treeGrid.treeOpenAll('treeTable', !treedata[0][treeGrid.config.cols.isOpen]);
    });
    $('#btnnew').on('click', function () {
        var checkStatus = treeGrid.checkStatus('treeTable')
            , rows = checkStatus.data;
        if (rows.length > 1) {
            zlContext.warnMsg("不能同时两个功能点下增加功能！");
            return;
        }
        formindex = layer.open({
            type: 1,
            id: 'addFunctionLayer',
            area: ['100%', '100%'],
            content: frm.join(''),
            title: "新增功能",
            success: function () {
                $('#addnew input[name="OBJNAME"]').val('');
                $('#addnew input[name="OBJCODE"]').val('');
                $('#addnew input[name="ICON_SMALL"]').val('');
                $('#addnew input[name="ICON_BIG"]').val('');
                $('#addnew input[name="RWID"]').val('');
                $('#addnew input[name="BEIZ"]').val('');
                $('#addnew input[name="type"]').val('add');
                
                $('#addnew input[name="ISLOGIN"][value=1]').attr("checked", true) ;
                $('#addnew input[name="ORGID"]').val($('input[name="ORGIDTEMP"]').val());
                selectChange();
                if (rows.length > 0) {
                    $('div[name="SYS_PARENTID"]').attr("value", rows[0].RWID);
                    $('div[name="SYS_PARENTID"]').attr("text", rows[0].OBJNAME);
                }
                addGroovyEdit();
                ObjnameChange();
                form.render();
            }
        });
    });

    function selectChange(url, RELE_RES_ID) {
        if (url && url.indexOf('isnewtab') > -1) {
            var setting = "{value:\'" + RELE_RES_ID + "\',placeholder:\'如果需要大屏展示请选择\', titlefield: \'OBJNAME\', valuefield: \'RWID\', method:\'POST\',dataurl:\'' + layui.cache['contentPath']+'/manager/largescreen/query\'}";
            $('#addnew select[name=daping]').attr('settings', setting);
            $('#addnew div[name="RELE_RES_ID"]').attr('value', '');
        }
        form.on('select(daping)', function (data) {
            if (data.value) {
                $('#addnew input[name="inputRELE_RES_ID"]').val('');
                $('#addnew input[name="RELE_RES_ID"]').val('');
                $('#addnew input[name="RES_ACTION"]').val('#{contentpath}/manager/largescreen/preview?RWID=' + data.value + '&isnewtab=1');
                $('#addnew input[name="RES_ACTION"]').attr('disabled', 'disabled');

            } else if ($('input[name="dapinginput"').val()) {
                $('#addnew input[name="RES_ACTION"]').val('');
                $('#addnew input[name="RES_ACTION"]').removeAttr('disabled');
            }
            $('input[name="dapinginput"').val(data.value);
        });
    }

    $('#btndel').on('click', function () {
        var checkStatus = treeGrid.checkStatus('treeTable')
            , rows = checkStatus.data;
        if (rows.length == 0) {
            zlContext.warnMsg("请选择需要删除的功能节点");
            return;
        }
        var canpost = true;
        for (var i = 0; i < rows.length; i++) {
            if (rows[i].children.length > 0) {
                zlContext.warnMsg(rows[i].OBJNAME + "功能节点下还有子功能，请先删除子功能");
                canpost = false;
                return;
            }
        }
        if (!canpost) {
            return;
        }
        zlContext.confirm('询问', '是否要删除选择的功能吗？', function (index) {
            //删除对应行（tr）的DOM结构
            //向服务端发送删除指令
            zlContext.deletePost(layui.cache['contentPath'] + '/manager/corefunction/del', rows, function (result) {
                if (result[statusName] == OK) {
                    treeGrid.reload('treeTable', {
                        url: layui.cache['contentPath'] + '/manager/corefunction/query',
                        method: 'POST'
                    });
                    form.render();
                    zlContext.successMsg('删除成功');
                }
                else {
                    zlContext.errorMsg(result[msgName]);
                }
                layer.close(index);
            });
        });
    });

    $('#btnedit').on('click', function () {
        var checkStatus = treeGrid.checkStatus('treeTable')
            , rows = checkStatus.data;
        if (rows.length == 0) {
            zlContext.warnMsg("请选择需要修改的功能节点！");
            return;
        } else if (rows.length > 1) {
            zlContext.warnMsg("每次只能勾选一个功能节修改！");
            return;
        }
        formindex = layer.open({
            type: 1,
            id: 'editFunctionLayer',
            area: ['100%', '100%'],
            title: "编辑功能信息",
            content: frm.join(''),
            success: function () {
                var orgid = $('input[name="ORGIDTEMP"]').val();
                var data = rows[0];
                // $('label[name="pfunction"]').html("上级功能节点(修改此值,其子节点也会跟随修改)")
                $('input[name="OBJNAME"]').val(data.OBJNAME);
                $('input[name="OBJCODE"]').val(data.OBJCODE);
                $('input[name="ICON_SMALL"]').val(data.ICON_SMALL);
                $('input[name="ICON_BIG"]').val(data.ICON_BIG);
                $('input[name="RWID"]').val(data.RWID);
                $('input[name="VISIBILITY"]').val(data.VISIBILITY);
                $('input[name="BEIZ"]').val(data.BEIZ);
                $('input[name="type"]').val('edit');
                $('input[name="SELORGID"]').val($('input[name="ORGIDTEMP"]').val());
                $('input[name="ORGID"]').val(data.ORGID);
                $('div[name="SYS_PARENTID"]').attr("value", data.SYS_PARENTID);
                $('input[name="RES_ACTION"]').val(data.RES_ACTION);
                $('textarea[name="DATAFILTER"]').val(data.DATAFILTER);
                if(!data.ISLOGIN||data.ISLOGIN==1){
                    $('input[name="ISLOGIN"][value=1]').attr("checked",true);
                }else{
                    $('input[name="ISLOGIN"][value=2]').attr("checked",true);
                }
                
                if (data.RELE_RES_ID) {
                    $('input[name=RES_ACTION]').attr('disabled', 'disabled');
                }
                $('div[name="RELE_RES_ID"]').attr("value", data.RELE_RES_ID);
                addGroovyEdit(data.DATAFILTER);
                ObjnameChange();
                selectChange(data.RES_ACTION, data.RELE_RES_ID);
                form.render();
            },
            cancel: function (index, layero) {
                newFormObj.newFields = null;
                if ($('#addnew').find('.getField').length == 0) {
                    $('#addnew').append('<button class="layui-btn layui-hide getField" lay-submit lay-filter="addfunction">获取表单值</button>');
                }
                var verifyItem = $('#addnew').find('[lay-verify]');
                for (var i = 0; i < verifyItem.length; i++) {
                    var verifyStr = $(verifyItem[i]).attr('lay-verify');
                    if (verifyStr != '') {
                        $(verifyItem[i]).attr({
                            'lay-verify': '',
                            'data-verifyflag': verifyStr
                        })
                    }
                }
                $('#addnew').find('.getField').trigger('click');
                if (newFormObj.newFields == null) {
                    return false;
                }
                if (newFormObj.newFields.daping) {
                    newFormObj.newFields.RELE_RES_ID = newFormObj.newFields.daping;
                }
                if (!zlContext.isObjectValueEqual(newFormObj.newFields, rows[0])) {
                    var changeConfirmLayer = layer.confirm('数据已有改动，是否要保存？', {
                        title: '是否关闭',
                        resize: false,
                        btn: ['保存关闭', '确定关闭', '取消'], //按钮
                        btnAlign: 'c',
                        anim: 1,
                        icon: 3
                    }, function () {
                        layer.close(changeConfirmLayer)
                        var items = $('#addnew').find('[data-verifyflag]')
                        for (var i = 0; i < items.length; i++) {
                            var verifyStr = $(items[i]).attr('data-verifyflag');
                            $(items[i]).attr({
                                'lay-verify': verifyStr,
                                'data-verifyflag': ''
                            });
                        }
                        $('#btnadd').trigger('click');
                    }, function () {
                        layer.close(index)
                    }, function () {
                        layer.close(changeConfirmLayer)
                    });
                    return false;
                } else {
                    layer.close(index)
                }
            }
        });
    });

    function addGroovyEdit(value) {
        $('#ace-editor-contianer').append('<div id="DATAFILTER" name="DATAFILTER" style="min-height: 245px; overflow-y: auto;"></div>');
        ace.require("ace/ext/language_tools");
        var aceEditor = ace.edit("DATAFILTER");
        aceEditor.setTheme("ace/theme/monokai");//monokai模式是自动显示补全提示
        aceEditor.getSession().setMode("ace/mode/groovy");//语言
        aceEditor.getSession().setTabSize(4);
        aceEditor.setFontSize(14);
        if (value) {
            aceEditor.setValue(value);
        }

        aceEditor.setOptions({
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true,//只能补全
        });

    }

    form.on('submit(addfunction)', function (data) {
        if ($(data.elem).hasClass('getField')) {
            newFormObj.newFields = data.field
            return false;
        }
        var aceEditor = ace.edit("DATAFILTER");
        var DATAFILTER = $.trim(aceEditor.getValue());
        data.field.DATAFILTER = DATAFILTER;
        if (data.field.daping) {
            data.field.RELE_RES_ID = data.field.daping;
        }
        var type = $('#addnew input[name="type"]').val();
        var url = layui.cache['contentPath'] + '/manager/corefunction/add';
        if (type == 'edit') {
            url = layui.cache['contentPath'] + '/manager/corefunction/modify';
            if (data.field.RWID == data.field.SYS_PARENTID) {
                zlContext.errorMsg('上级功能不能为自身');
                return false;
            }
        }
        zlContext.post(
            url,
            data.field,
            function (data) {
                if (data[statusName] == OK) {
                    layer.close(formindex);
                    treeGrid.reload('treeTable', {
                        url: layui.cache['contentPath'] + '/manager/corefunction/query',
                        method: 'POST'
                    });
                    zlContext.successMsg('保存成功');
                } else {
                    zlContext.errorMsg(data[msgName]);
                }
            }
        );
        return false;
    });

    function ObjnameChange() {
        $('input[name="OBJNAME"]').change(function () {
            var v = $('input[name="OBJNAME"]').val();
            $('input[name="OBJCODE"]').val(zlPinYin.C(v));
        });
    }

    //当浏览器窗口大小改变时，设置显示内容的高度  
    window.onresize = function () {
        fullheight = zlContext.setMaxHeihgt(0);
    }

    $('#btnSeacher').on('click', function () {
        isloadsearch = true;
        var seachervalue = $('#edtSeacherValue').val();
        treeGrid.reload('treeTable', {
            url: layui.cache['contentPath'] + '/manager/corefunction/query',
            method: 'POST',
            where: { searchvalue: seachervalue }
        });
    });

    $('#edtSeacherValue').on('keyup', function (event) {
        var keyCode = event.keyCode;
        if (keyCode == 13) {
            $('#btnSeacher').trigger('click');
        }
        if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
            $('#btnSeacher').trigger('click');
            isloadsearch = false;
        }
    });
    var formulaCallback = {
        callbackFormula: function (param) {
            var aceEditor = ace.edit("DATAFILTER");
            aceEditor.setValue(param['MODELE_VALUE']);
            layer.close(param.addformulaPop);
        }
    };
    $("body").on('click', '#addnew .custom-formula-btn', function () {
        var aceEditor = ace.edit("DATAFILTER");
        var text = aceEditor.getValue();
        var formulaSettings = "{'dataurl':'" + layui.cache['contentPath'] + "/manager/coremodeldesign/queryFormulaDesc','method':'post','isordinary':false}";
        zlFormulaCmp.render($('[zl-action="formula"]'), text, formulaSettings, formulaCallback);
    });
});  